package com.qfedu.common.core.exception;

import com.qfedu.common.core.common.R;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname GlobalExceptionHandler
 * @Description TODO
 * @Date 2025-05-27 15:59
 * @Created by 老任与码
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return R.fail(message);
    }

    // 验证框架的异常处理
    @ExceptionHandler(ConstraintViolationException.class)
    public R constraintViolationException(ConstraintViolationException ex) {
        // 获取对应的迭代器
        Iterator<ConstraintViolation<?>> iterator = ex.getConstraintViolations().iterator();
        String message = null;
        while (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            // 获取异常信息
            // System.out.println(next.getMessage());
            message = next.getMessage();
            break;
        }
        return R.fail(message);
    }

    // 处理其他异常
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {
        e.printStackTrace();
        return R.fail("未知异常，请联系客服");
    }
}
